package com.immoc.jdbc.sample;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.immoc.jdbc.common.DbUtils;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;

public class DruidSample {
    public static void main(String[] args) {
        // 1. 加载配置文件
        Properties properties = new Properties();
        String pFile = DruidSample.class.getResource("/druid-config.properties").getPath();
        try {
            pFile =  URLDecoder.decode(pFile,"UTF-8");
            properties.load(new FileInputStream(pFile));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 2. 获取DataSource数据源对象
        Connection connection = null;
        ResultSet rs = null;
        try {
            DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
            // 3. 创建数据库链接
            connection = dataSource.getConnection();
            PreparedStatement preparedStatement = connection.prepareStatement("select * from employee limit 0,10");
            rs = preparedStatement.executeQuery();
            while(rs.next()){
                Integer eno = rs.getInt(1);
                String ename = rs.getString("ename");
                Float salary = rs.getFloat("salary");
                System.out.println(eno + "-" + ename +"-"+ salary);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            /**
             * 使用连接池时候 conn.close() 是将连接回收至连接池
             */
            DbUtils.closeConnection(connection);
        }
    }
}
